<script setup>
import { ref, onMounted, computed } from 'vue'
import axios from 'axios'
import {ElMessage, ElMessageBox} from 'element-plus'
import {CirclePlus, Key, Plus, Refresh, Search, User} from '@element-plus/icons-vue'

// 表格数据
const tableData = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
// 控制添加对话框显示
const addDialogVisible = ref(false)

// 添加表单数据
const addForm = ref({
  name: '',
  no: '',
  sex: '男',
  age: '',
  phone: '',
  roleId: null
})
// 打开添加对话框
const handleAdd = () => {
  addForm.value = {
    name: '',
    no: '',
    sex: '男',
    age: '',
    phone: '',
    roleId: null
  }
  addDialogVisible.value = true
}
// 提交新增
const submitAdd = async () => {
  try {
    // 基础验证
    if (!addForm.value.name.trim() || !addForm.value.no.trim()) {
      ElMessage.warning('姓名和账号为必填项')
      return
    }

    const response = await axios.post('http://localhost:8080/user/save', {
      ...addForm.value,
      roleId: Number(addForm.value.roleId)
    })

    if (response.data) {
      ElMessage.success('新增成功')
      addDialogVisible.value = false
      await fetchUsers() // 刷新数据
    }
  } catch (error) {
    ElMessage.error('新增失败')
    console.error('新增错误:', error)
  }
}
// 编辑表单数据
const editForm = ref({
  id: null,
  name: '',
  sex: '',
  age: '',
  phone: '',
  roleId: null
})
// 编辑操作
const handleEdit = (row) => {
  editForm.value = { ...row }
  dialogVisible.value = true
}

// 提交编辑
const submitEdit = async () => {
  try {
    const response = await axios.put('http://localhost:8080/user/update', editForm.value)
    if (response.data) {
      ElMessage.success('修改成功')
      dialogVisible.value = false
      await fetchUsers() // 刷新数据
    }
  } catch (error) {
    ElMessage.error('修改失败')
    console.error('更新错误:', error)
  }
}
// 删除操作
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定删除用户 ${row.name} 吗？`, '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await axios.delete('http://localhost:8080/user/delete', {
      params: { id: row.id }
    })

    if (response.data) {
      ElMessage.success('删除成功')
      await fetchUsers() // 刷新数据
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error('删除错误:', error)
    }
  }
}
// 分页参数
const pagination = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 查询参数
const queryParams = ref({
  name: '',
  no: '',
  roleId: null
})

// 获取用户数据
const fetchUsers = async () => {
  loading.value = true
  try {
    // 清理空值参数
    const cleanParams = {
      name: queryParams.value.name.trim(),
      no: queryParams.value.no.trim(),
      roleId: queryParams.value.roleId !== null
          ? Number(queryParams.value.roleId)
          : null
    }

    console.log('请求参数:', cleanParams) // 调试日志

    const response = await axios.post('http://localhost:8080/user/listPage', {
      pageNum: pagination.value.pageNum,
      pageSize: pagination.value.pageSize,
      param: cleanParams
    })

    tableData.value = response.data.data
    pagination.value.total = response.data.total
  } catch (error) {
    console.error('请求失败:', error)
    ElMessage.error('数据加载失败')
  } finally {
    loading.value = false
  }
}

// 查询操作
const handleQuery = () => {
  pagination.value.pageNum = 1
  fetchUsers()
}

// 重置查询
const resetQuery = () => {
  queryParams.value = { name: '', no: '', roleId: null }
  handleQuery()
}

// 分页变化
const handlePageChange = (newPage) => {
  pagination.value.pageNum = newPage
  fetchUsers()
}

// 初始化加载
onMounted(fetchUsers)

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(pagination.value.total / pagination.value.pageSize)
})

</script>

<template>
  <el-main class="main-content">
    <el-scrollbar>
      <!-- 查询表单 -->
      <div class="query-form">
        <el-form :inline="true" :model="queryParams">
          <el-form-item label="姓名">
            <el-input
                v-model.trim="queryParams.name"
                placeholder="请输入姓名"
                clearable
                @keyup.enter="handleQuery"
                class="search-input"
            >
              <template #prefix>
                <el-icon class="input-icon">
                  <User />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="账号">
            <el-input
                v-model.trim="queryParams.no"
                placeholder="请输入账号"
                clearable
                @keyup.enter="handleQuery"
                class="search-input"
            >
              <template #prefix>
                <el-icon class="input-icon">
                  <Key />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="身份">
            <el-select
                v-model="queryParams.roleId"
                placeholder="请选择身份"
                clearable
                class="role-select"
                placement="bottom-start"
            >
              <el-option label="超级管理员" :value="0" />
              <el-option label="管理员" :value="1" />
              <el-option label="普通账号" :value="2" />
            </el-select>
          </el-form-item>

          <el-form-item class="action-buttons">
            <el-button
                type="primary"
                :loading="loading"
                @click="handleQuery"
                class="query-btn"
            >
              <el-icon class="mr-1"><Search /></el-icon>
              查询
            </el-button>
            <el-button
                @click="resetQuery"
                class="reset-btn"
            >
              <el-icon class="mr-1"><Refresh /></el-icon>
              重置
            </el-button>
            <el-button
                type="success"
                :loading="loading"
                @click="handleAdd"
                class="add-btn"
            >
              <el-icon class="mr-1"><CirclePlus /></el-icon>
              新增
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <el-table
          :data="tableData"
          height="calc(100vh - 120px)"
          v-loading="loading"
          class="data-table"
      >
        <!-- 表格列定义 -->
        <el-table-column prop="id" label="ID" width="140" />
        <el-table-column prop="name" label="姓名" width="180" />
        <el-table-column prop="no" label="账号" width="180" />
        <el-table-column prop="sex" label="性别" width="120"/>
        <el-table-column prop="age" label="年龄" width="120" />
        <el-table-column prop="phone" label="电话" width="180" />
        <el-table-column prop="roleId" label="身份" width="150">
          <template #default="{ row }">
            <el-tag
                :type="{
                0: 'danger',
                1: 'warning',
                2: 'success'
              }[row.roleId]"
                effect="dark"
            >
              {{ ['超级管理员', '管理员', '普通账号'][row.roleId] || '未知身份' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>

        <!-- 分页 -->
        <template #append>
          <div class="pagination-wrapper">
            <div class="pagination-info">
              共 {{ pagination.total }} 条，第 {{ pagination.pageNum }}/{{ totalPages }} 页
            </div>
            <el-pagination
                :current-page="pagination.pageNum"
                :page-size="pagination.pageSize"
                :total="pagination.total"
                layout="prev, pager, next"
                @current-change="handlePageChange"
                class="custom-pagination"
            />
          </div>
        </template>
      </el-table>
      <!-- 编辑对话框 -->
      <el-dialog v-model="dialogVisible" title="用户编辑" width="30%">
        <el-form :model="editForm" label-width="80px">
          <el-form-item label="姓名">
            <el-input v-model="editForm.name" clearable />
          </el-form-item>
          <el-form-item label="账号">
            <el-input v-model="editForm.no" clearable />
          </el-form-item>
          <el-form-item label="性别">
            <el-select v-model="editForm.sex">
              <el-option label="男" value="男" />
              <el-option label="女" value="女" />
            </el-select>
          </el-form-item>
          <el-form-item label="年龄">
            <el-input v-model="editForm.age" type="number" clearable />
          </el-form-item>
          <el-form-item label="电话">
            <el-input v-model="editForm.phone" clearable />
          </el-form-item>
          <el-form-item label="身份" aria-readonly="true">
            <el-select v-model="editForm.roleId" disabled>
              <el-option label="超级管理员" :value="0" />
              <el-option label="管理员" :value="1" />
              <el-option label="普通账号" :value="2" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEdit">确认</el-button>
        </template>
      </el-dialog>

      <!-- 新增用户对话框 -->
      <el-dialog v-model="addDialogVisible" title="新增用户" width="30%">
        <el-form :model="addForm" label-width="80px">
          <el-form-item label="姓名" required>
            <el-input v-model.trim="addForm.name" clearable />
          </el-form-item>
          <el-form-item label="账号" required>
            <el-input v-model.trim="addForm.no" clearable />
          </el-form-item>
          <el-form-item label="性别">
            <el-select v-model="addForm.sex">
              <el-option label="男" value="男" />
              <el-option label="女" value="女" />
            </el-select>
          </el-form-item>
          <el-form-item label="年龄">
            <el-input v-model.number="addForm.age" type="number" clearable />
          </el-form-item>
          <el-form-item label="电话">
            <el-input v-model="addForm.phone" clearable />
          </el-form-item>
          <el-form-item label="密码" required>
            <el-input v-model.trim="addForm.password" type="password" clearable />
          </el-form-item>
          <el-form-item label="身份">
            <el-select v-model="addForm.roleId">
              <el-option label="超级管理员" :value="0" />
              <el-option label="管理员" :value="1" />
              <el-option label="普通账号" :value="2" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAdd">确认</el-button>
        </template>
      </el-dialog>
    </el-scrollbar>
  </el-main>
</template>

<style scoped>
/* 主内容区 */
.main-content {
  padding: 0 !important;
  background: #f8fafc;
}

/* 查询表单 */
.query-form {
  padding: 16px 24px;
  background: #fff;
  margin: 16px;
  border-radius: 8px;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

/* 输入框样式 */
.search-input {
  width: 240px;
}

:deep(.el-input__wrapper) {
  border-radius: 6px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.06) !important;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2) !important;
}

.input-icon {
  color: #64748b;
  margin-right: 8px;
}

/* 下拉选择框 */
.role-select {
  width: 180px;
}

:deep(.el-select-dropdown) {
  border-radius: 6px;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}

:deep(.el-select-dropdown__item) {
  padding: 0 20px;
  height: 36px;
  line-height: 36px;
  transition: all 0.2s;
}

:deep(.el-select-dropdown__item.selected) {
  background-color: #f1f5f9;
}

/* 操作按钮 */
.action-buttons {
  margin-left: auto;
}

.query-btn,
.reset-btn {
  padding: 8px 20px;
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.query-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 6px -1px rgba(64, 158, 255, 0.2);
}

.reset-btn:hover {
  color: #409EFF;
  border-color: #c6e2ff;
  background-color: #ecf5ff;
}

/* 数据表格 */
.data-table {
  margin: 0 16px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

:deep(.el-table__header th) {
  background-color: #f8fafc !important;
  font-weight: 600;
}

/* 分页样式 */
.pagination-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 24px;
  background: #fff;
  border-top: 1px solid #e2e8f0;
}

.custom-pagination {
  :deep(.btn-prev),
  :deep(.btn-next) {
    border-radius: 6px;
    padding: 0 12px;
  }
}
.mr-1 {
  margin-right: 0.01rem;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .query-form {
    padding: 12px;
    margin: 8px;
  }

  .el-form-item {
    width: 100%;
    margin-right: 0 !important;
  }

  .search-input {
    width: 100%;
  }

  .action-buttons {
    width: 100%;
    margin-top: 12px;
  }

  .query-btn,
  .reset-btn {
    width: 100%;
    margin-top: 8px;
  }

  .pagination-wrapper {
    flex-direction: column;
    gap: 8px;
    padding: 12px;
  }
}
/* 添加对话框动画 */
.el-dialog {
  transition: all 0.3s ease-out;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .el-dialog {
    width: 90% !important;
  }
}
.add-btn {
  background-color: #67c23a;
  border-color: #67c23a;
  color: white;
}
.add-btn:hover {
  background-color: #5daf34;
  border-color: #5daf34;
}

</style>
